<template>
    <div style="height: 5%;display: flex;">
        <div  >
            &nbsp; &nbsp;
            <n-button strong secondary @click="back()" text type="primary">
                <jb-icon :local="true" icon="ri:arrow-left-double-fill" height="30"></jb-icon> &nbsp;&nbsp; 返回
            </n-button>
        </div>
    </div>
    <jb-crud-page ref="pageRef" :searchUrl="pageUrl" :conditions-align="'start'"
                  :searchConditions="pageConditions" @afterSearch="handleAfterSearch"
                  @afterRender="handleAfterRender" style="height: 90%">
        <template #conditions-form>
            <jb-input v-model:value="pageConditions.keywords" placeholder="请输入名称" clearable/>
        </template>
        <template #default="{list,tableStartIndex}">
            <n-layout has-sider>
                <n-layout>
                    <jb-table
                        ref="tableRef"
                        :row-config="{keyField: 'id', isHover: true}"
                        :radio-config="{ trigger: 'row', checkRowKey: selectRow?.id }"
                        :data="list"
                        :start-index="tableStartIndex"
                        @radio-change="radioChangeEvent"
                    >
                        <vxe-column type="radio" width="60" fixed="left">
                            <template #header>
                                <vxe-button mode="text" @click="clearRadioRowEvent" :disabled="!selectRow"></vxe-button>
                            </template>
                        </vxe-column>
                        <jb-column type="seq" title="序号" width="60" fixed="left"></jb-column>
                        <jb-column
                            field="name"
                            title="名称"
                            min-width="200"
                            fixed="left"
                        ></jb-column>
                        <jb-column
                            field="briefInfo"
                            title="简介"
                            min-width="280"
                        ></jb-column>

                    </jb-table>
                </n-layout>

            </n-layout>

        </template>

    </jb-crud-page>
    <div class="flex justify-center" style="height: 5%;align-items: end;">
        <jb-btn type="primary" @click="submit">提交-挂载知识库</jb-btn>
    </div>

</template>

<script setup>
import {useResetableData} from "@/hooks/common/use-resetable-data.js";
import {onMounted, ref} from "vue";
import {JBoltApi} from "@/service/request/index.js";
import {useMessage} from 'naive-ui'

const message = useMessage()

const props = defineProps({
    appId: String
})
const emits = defineEmits(['closeKnowledge'])

const pageRef = ref(null)
const pageUrl = ref('')
const pageConditions = useResetableData({
    keywords: '',
    enabled: true
})

const tableRef = ref(null)

const selectRow = ref(null)

// 单选事件处理
function radioChangeEvent({row}) {
    console.log(row);
    selectRow.value = row
}

function clearRadioRowEvent() {
    const $table = tableRef.value
    if ($table) {
        $table.clearRadioRow()
        selectRow.value = null
    }
}

const resultList = ref([])

function handleAfterSearch(list) {
    resultList.value = list
}

function handleAfterRender(list) {
    const $table = tableRef.value
    if ($table) {
        $table.setRadioRow(selectRow.value)
    }
}

function back() {
    emits('closeKnowledge')
}

//保存知识库
const submit = async () => {

    if (selectRow.value) {
        JBoltApi.tryPost('/aiApp/submitKnowledgeBases', {
            appId: props.appId,
            list: [selectRow.value.id]
        }).then((res) => {
            message.success('保存成功');
            // 保存成功后触发关闭弹窗事件
            emits('closeKnowledge')
        }).catch(error => {
            console.error(error)
        })


    } else {
        message.error('请选择知识库');
    }
}

// const submit = async (callback) => {
//     // console.log(selectRow.value.id);
//     if (selectRow.value) {
//         await JBoltApi.post('/aiApp/submitKnowledgeBases', {
//             appId: props.appId,
//             list: [selectRow.value.id]
//         })
//
//         if (callback) {
//             callback()
//         }
//         return true
//     }
// }

defineExpose({
    submit
})

let showTable = ref(false)

function loadSelectedList() {
    JBoltApi.tryGet('/aiApp/getKlbByAppId', {
        appId: props.appId
    }).then(res => {
        if (res.data != null) {
            selectRow.value = {name: res.data[0].value, id: res.data[0].key}
        }
        showTable.value = true
        pageUrl.value = '/aiKnowledgeBase/list?enable='+true
    }).catch(error => {
        console.error(error)
    })
}

onMounted(() => {

    if (props.appId) {
        loadSelectedList()
    }
})

</script>


<style scoped>


</style>